//
//  BIDServiceForResidentViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/5/20.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDServiceForResidentViewController.h"
#import "BIDLoadWebPageViewController.h"
#import "BIDServicePhoneCell.h"

//便民小贴士
static NSString *tipListURL = @"lifeTipsAndroid/list.action";
//服务电话
static NSString *servicePhoneListURL = @"lifeServeAndroid/list.action";

@interface BIDServiceForResidentViewController ()<BIDServicePhoneCellDelegate, BIDBaseListViewDelegate>
{
    NSMutableArray *_tipArr;
    NSMutableArray *_servicePhoneArr;
    NSUInteger _curSelectIndex;
    NSUInteger _curPageForTip;
    NSUInteger _curPageForServicePhone;
    BOOL _bRegister;
    BIDServicePhoneCell *_tempCell;
}
@end

@implementation BIDServiceForResidentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden = NO;
    _curSelectIndex = 0;
    _curPageForTip = 0;
    _curPageForServicePhone = 0;
    _tipArr = [NSMutableArray array];
    _servicePhoneArr = [NSMutableArray array];
    _tempCell = [[[NSBundle mainBundle] loadNibNamed:@"BIDServicePhoneCell" owner:self options:nil] lastObject];
    [self prepareForLayout];
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)prepareForLayout
{
    UISegmentedControl *segmentedCtrl = [[UISegmentedControl alloc] initWithItems:@[@"便民小贴士", @"服务电话"]];
    segmentedCtrl.selectedSegmentIndex = 0;
    [segmentedCtrl addTarget:self action:@selector(segmentedCtrlHandler:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = segmentedCtrl;
}

- (void)loadData
{
    self.curPage++;
    NSString *strDesURL = @"";
    switch(_curSelectIndex)
    {
        case 0:
        {
            _curPageForTip = self.curPage;
            strDesURL = tipListURL;
            self.dataSourceArr = [[NSMutableArray alloc] initWithArray:_tipArr];
        }
            break;
        case 1:
        {
            _curPageForServicePhone = self.curPage;
            strDesURL = servicePhoneListURL;
            self.dataSourceArr = [[NSMutableArray alloc] initWithArray:_servicePhoneArr];
        }
            break;
    }
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], strDesURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@&page=%ld&rows=%ld", [AppDelegate getUserId], self.curPage, self.countPerPage];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            [self.dataSourceArr addObjectsFromArray:responseDic[@"rows"]];
            if(self.dataSourceArr.count < self.curPage*self.countPerPage)
            {
                [self.myTableView hasNoMoreData];
            }
            else
            {
                [self.myTableView hasMoreData];
            }
            [self.myTableView reloadData];
        }
        [self autoDecideToShowEmptyView];
    }];
}

- (void)segmentedCtrlHandler:(UISegmentedControl *)segmentedCtrl
{
    _curSelectIndex = segmentedCtrl.selectedSegmentIndex;
    switch(_curSelectIndex)
    {
        case 0:
        {
            _servicePhoneArr = [[NSMutableArray alloc] initWithArray:self.dataSourceArr];
            self.curPage = _curPageForTip;
            self.dataSourceArr = [[NSMutableArray alloc] initWithArray:_tipArr];
        }
            break;
        case 1:
        {
            _tipArr = [[NSMutableArray alloc] initWithArray:self.dataSourceArr];
            self.curPage = _curPageForServicePhone;
            self.dataSourceArr = [[NSMutableArray alloc] initWithArray:_servicePhoneArr];
        }
            break;
    }
    if(self.dataSourceArr.count==0)
    {
        [self loadData];
    }
    else
    {
        [self.myTableView reloadData];
    }
}

- (void)callWithPhone:(NSString *)phone
{
    NSString *str = [[NSString alloc] initWithFormat:@"tel://%@", phone];
    NSURL *url = [NSURL URLWithString:str];
    UIWebView *telWebView = [[UIWebView alloc] init];
    [telWebView loadRequest:[NSURLRequest requestWithURL:url]];
    [self.view addSubview:telWebView];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *identifier = @"identifier";
    NSUInteger row = indexPath.row;
    NSDictionary *dic = self.dataSourceArr[row];
    if(!_bRegister)
    {
        _bRegister = YES;
        UINib *nib = [UINib nibWithNibName:@"BIDServicePhoneCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:@"cell"];
    }
    if(_curSelectIndex == 1)
    {
        BIDServicePhoneCell *servicePhoneCell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        servicePhoneCell.titleLabel.text = dic[@"name"];
        servicePhoneCell.phoneLabel.text = dic[@"telephone"];
        servicePhoneCell.locationLabel.text = dic[@"address"];
        cell = servicePhoneCell;
    }
    else
    {
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if(!cell)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.textLabel.text = dic[@"title"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSUInteger row = indexPath.row;
    NSDictionary *dic = self.dataSourceArr[row];
    if(_curSelectIndex == 0)
    {
        NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[dic[@"content"] dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
        BIDLoadWebPageViewController *vc = [[BIDLoadWebPageViewController alloc] initWithNibName:@"BIDLoadWebPageViewController" bundle:nil];
        vc.webContent = attrStr.string;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        NSString *strPhone = dic[@"telephone"];
        [self callWithPhone:strPhone];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 44.f;
    if(_curSelectIndex == 1)
    {
        _tempCell.locationLabel.preferredMaxLayoutWidth = CGRectGetWidth(tableView.frame) - 48;
        _tempCell.locationLabel.text = @"";
        CGSize size =  [_tempCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
        height = size.height<88 ? 88 : size.height+1;
    }
    else
    {
    }
    return height;
}

@end
